package com.itheima.server.service;

import com.itheima.server.exception.BusinessException;
import com.itheima.tanhua.autoconfig.template.AipFaceTemplate;
import com.itheima.tanhua.autoconfig.template.OssTemplate;
import com.itheima.tanhua.dubbo.api.UserInfoApi;
import com.itheima.tanhua.model.vo.ErrorResult;
import com.itheima.tanhua.model.vo.UserInfoVo;
import com.itheima.tanhua.model.domain.UserInfo;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@Service
public class UserInfoService {

    @DubboReference
    private UserInfoApi userInfoApi;

    @Autowired
    private OssTemplate ossTemplate;

    @Autowired
    private AipFaceTemplate aipFaceTemplate;



    /**
     * 保存用户信息
     *
     * @param userInfo
     */
    public void save(UserInfo userInfo) {
        userInfoApi.save(userInfo);
    }

    public void updateHead(MultipartFile headPhoto, Long userId) throws IOException {
        //先利用OOS上传图片
        String imgUrl = ossTemplate.upload(headPhoto.getOriginalFilename(), headPhoto.getInputStream());

        //调用百度云人脸识别判断是否包含人脸
        boolean detect = aipFaceTemplate.detect(imgUrl);

        //不包含人脸抛出异常
        if (!detect) {
            throw new BusinessException(ErrorResult.faceError());
        }

        //包含人脸调用方法进行头像更新
        UserInfo userInfo = new UserInfo();
        userInfo.setId(userId);
        userInfo.setAvatar(imgUrl);

        userInfoApi.update(userInfo);
    }

    /**
     * 根据id查找
     *
     * @param userId
     * @return
     */
    public UserInfoVo findById(Long userId) {
        UserInfo userInfo = userInfoApi.findById(userId);

        UserInfoVo userInfoVo = new UserInfoVo();

        BeanUtils.copyProperties(userInfo,userInfoVo);


        return userInfoVo;
    }

    /**
     * 根据id更新用户信息
     * @param userInfo
     */
    public void update(UserInfo userInfo) {
        userInfoApi.update(userInfo);
    }
}
